<?php

namespace App\Dao;

use App\Model\GoodsModel;

class GoodsDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = GoodsModel::query();

        $query->when(checkIsHasField($params,'goods_id'),function ($query)use ($params){
            $query->where('goods_id',$params['goods_id']);
        });

        $query->when(checkIsHasField($params,'status_del'),function ($query)use ($params){
            $query->where('status_del',$params['status_del']);
        });


        $query->when(checkIsHasField($params,'category_id'),function ($query)use ($params){
            $query->where('category_id',$params['category_id']);
        });
        $query->when(checkIsHasField($params,'show'),function ($query)use ($params){
            $query->where('show',$params['show']);
        });


        return $query;
    }

    public static function add($params = [])
    {
        checkForData(
            ['category_id','mix_goods_price','goods_name','goods_img_cover','goods_price','max_recive'],
            ['请选择商品分类','请输入商品分红值','请输入商品名称','请上传商品照片','请输入价格','请输入最大收益'],
            $params
        );
        if (self::builder_query()->create($params) === false)
            self::error('创建失败');
    }

    public static function pageinate(array $all): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query($all)->where('status_del',0)->paginate();
    }

    public static function goods($params = [])
    {
        return self::builder_query($params)->get();
    }

    public static function goods_info(array $all)
    {
        return self::builder_query([
            'goods_id'=>$all['goods_id']
        ])->first()->toArray();
    }

    public static function update(array $params)
    {
        checkForData(
            ['category_id','mix_goods_price','goods_name','goods_img_cover','goods_price','max_recive'],
            ['请选择商品分类','请输入分红值','请输入商品名称','请上传商品照片','请输入价格','请输入最大收益'],
            $params
        );
        if(self::builder_query(['goods_id'=>self::deleteParamId($params,'goods_id')])->update(self::filterFields($params,new GoodsModel())) === false){
            self::error('修改失败');
        }
    }

    public static function delete(array $params)
    {
        if(self::builder_query(['goods_id'=>$params['id']])->update([
            'status_del'=>1
        ]) === false){
            self::error('删除失败');
        }
    }
}
